//
//  LBLocationManager.m
//  LBCityPickerViewController
//
//  Created by LINAICAI on 2018/1/11.
//

#import "LBLocationManager.h"
#import <CoreLocation/CoreLocation.h>
#import <LBToastView/LBToastView.h>
#import <LBAlert.h>
static LBLocationManager *manager = nil;
@interface LBLocationManager()<CLLocationManagerDelegate>
@property (nonatomic , copy)void(^complete)(NSString *);
@property (nonatomic , strong)NSString *currentCityName;
//位置管理器
@property (nonatomic , strong)CLLocationManager *locationManager;
@end
@implementation LBLocationManager
+ (instancetype)shared{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[LBLocationManager alloc]init];
    });
    return manager;
}
- (void)getCurrentLocationWith:(void(^)( NSString * _Nullable ))complete{
    manager.complete = [complete copy];
    manager.currentCityName = @"";
    if ([CLLocationManager locationServicesEnabled])
    {
        if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusNotDetermined) {
            //用户还没做出选择
            [manager.locationManager requestWhenInUseAuthorization];
            [manager.locationManager startUpdatingLocation];
        }
        else if([CLLocationManager authorizationStatus]==kCLAuthorizationStatusRestricted){
            //用户暂时无法做出选择
            [manager.locationManager requestWhenInUseAuthorization];
            [manager.locationManager startUpdatingLocation];
        }
        else if([CLLocationManager authorizationStatus]==kCLAuthorizationStatusDenied){
            //被用户拒绝的授权
            [LBAlert ask:^(NSInteger answer) {
                if (answer == 1) {
                    NSString *url = @"App-Prefs:root=LOCATION_SERVICES";
                    if ([[UIApplication sharedApplication]canOpenURL:[NSURL URLWithString:url]]) {
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
                    }
                    
                }
            } message:@"定位权限未获取到" buttons:@[@"取消",@"重新去打开"]];
            if (manager.complete) {
                manager.complete(nil);
            }
            return;
        }
        else{
            [manager.locationManager startUpdatingLocation];
        }
        
        
    }
    else{
        [LBAlert ask:^(NSInteger answer) {
            if (answer == 1) {
                NSString *url = @"App-Prefs:root=LOCATION_SERVICES";
                if ([[UIApplication sharedApplication]canOpenURL:[NSURL URLWithString:url]]) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
                }
                
            }
        } message:@"定位服务未打开" buttons:@[@"取消",@"去打开"]];
        if (manager.complete) {
            manager.complete(nil);
        }
        return;
        
    }
    
}
- (CLLocationManager *)locationManager{
    if (!_locationManager) {
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
    }
    return _locationManager;
}
#pragma mark --
#pragma mark -- LocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray<CLLocation *> *)locations{
    if (locations.count) {
        [manager stopUpdatingLocation];
        
        CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
        [geoCoder reverseGeocodeLocation:locations.firstObject completionHandler:^(NSArray *placemarks, NSError *error) {
            if (placemarks.firstObject) {
                NSDictionary *dic = [placemarks.firstObject addressDictionary];
                NSString *city = [dic valueForKey:@"City"];
                if (self.complete && ![self.currentCityName isEqualToString:city]) {
                    self.currentCityName = city;
                    self.complete(self.currentCityName);

                }
            }
            else{
                if (self.complete) {
                    self.complete(nil);
                }
            }
            
        }];
    }
    else{
        if (self.complete) {
            self.complete(nil);
        }
    }
    
}


-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSString *errorString;
    [manager stopUpdatingLocation];
    switch([error code])
    {
        case kCLErrorDenied:
            //Access denied by user
            errorString = @"没有权限";
            //Do something...
            break;
        case kCLErrorLocationUnknown:
            //Probably temporary...
            errorString = @"未知位置";
            //Do something else...
            break;
        default:
            errorString = @"未知错误";
            break;
    }
    if (self.complete) {
        self.complete(nil);
    }
    
    
}

@end
